'''
Created on 23/09/2012

@author: Charles Murray
'''

import xml.etree.ElementTree as ET
from Container import *
from Model import *
from Next import *
from Subtree import *
class Parser(object):
    '''
    classdocs
    '''

    linkList = []

    def __init__(self, filename):
        '''
        Constructor
        '''
        self.tree = ET.parse(filename)
        self.root = self.tree.getroot()
        #parse(root)
                
    def parse(self, root):        
        if not list(root):
            return self.tag(root)
        else:
            subtree = []
            for child in root:
                subtree.append(self.parse(child))
            subtree = Subtree(subtree)
            return self.tag(root, subtree)
            
    def tag(self, root, subtree=None):
        if root.tag == "container":
            attributes = root.attrib
            return Container(attributes["mapping"], attributes["start"], attributes["end"], attributes["id"], "",subtree)
        elif root.tag == "next":
            attributes = root.attrib
            next = Next(attributes["id"])
            self.linkList.append(next)
            return next
        elif root.tag == "option":
            attributes = root.attrib
            return Option(attributes["condition"], subtree)
        elif root.tag == "model":
            attributes = root.attrib
            return Model(attributes["start"], attributes["end"], subtree)
                
    def linkTags(self, model):
        for next in self.linkList:
            self.traverse(model, next)
    """
    Goes through the model that has been generated and connects the next object to 
    the object with the id that it should be pointing to. At some point I will have 
    to make sure that we check for multiple of the same id.
    """        
    def traverse(self, model, next):
        if not model.getSubtree():
            return next
        for child in model.getSubtree():
            if child.getId() == next.getId():
                next.setLink(child)
            else:
                traverse(child, next)
        return next
            
    def getLinkList(self):
        return self.linkList
             
    
    def getRoot(self):
        return self.root
